package com.ysxsoft.wdg.ui.activity.my;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.classic.common.MultipleStatusView;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.google.gson.Gson;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.JsonBean;
import com.ysxsoft.wdg.bean.UserInfoBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.util.GetJsonDataUtil;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.camera.CameraUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.alertview.AlertView;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;
import com.ysxsoft.wdg.widget.alertview.OnItemClickListener;

import org.json.JSONArray;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class PersonActivity extends BaseActivity {

    private int sex;
    private String province;
    private String city;
    private String county;
    private int add_status;

    public static void start(Context context){
        Intent intent = new Intent(context,PersonActivity.class);
        context.startActivity(intent);
    }


    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.iv_tx)
    ImageView ivTx;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_qy)
    TextView tvQy;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private String uid = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person;
    }

    @Override
    protected void initData() {
        initStatusBar(topView,false);
        titleContent.setText("个人资料");

        uid = SharePrefUtils.getUserId();
        handler.sendEmptyMessage(MSG_LOAD_DATA);

        getUserInfo();
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        getUserInfo();
    }

    private void getUserInfo() {
        multStatusView.showLoading();
        mApiHelper.getUserInfo(uid, new Observer<BaseBean<UserInfoBean>>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<UserInfoBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    UserInfoBean infoBean = baseBean.getData();

                    tvUsername.setText(infoBean.getNickname());
                    tvId.setText(infoBean.getUid());
                    sex = infoBean.getSex();
                    tvSex.setText( sex == 0?"男":"女");

                    add_status = infoBean.getAdd_status();
                    tvQy.setText(infoBean.getProvince()+infoBean.getCity()+infoBean.getCounty());

                    ViewUtils.loadCircleImage(mContext,infoBean.getAvatar(),ivTx);
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                multStatusView.showContent();
            }
        });
    }

    @Override
    protected void setListener() {

    }


    @OnClick({R.id.title_finish, R.id.iv_tx, R.id.tv_username, R.id.tv_sex, R.id.tv_qy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.iv_tx:
                AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0){
                            new RxPermissions(PersonActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().takeCamera(PersonActivity.this);
                                        }
                                    });
                        }else if (position == 1){
                            new RxPermissions(PersonActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().openAlbum(PersonActivity.this);
                                        }
                                    });
                        }
                    }
                }).show();
                break;
            case R.id.tv_username:
                ModifyNickActivity.start(mContext,tvUsername.getText().toString().trim());
                break;
            case R.id.tv_sex:
                ModifySexActivity.start(mContext,sex);
                break;
            case R.id.tv_qy:
                if (add_status == 0){//0地址可修改1不可修改
                    selectAddress();
                }else {
                    ToastUtils.showToast("地址已更新过一次，无法修改");
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                CameraUtils.getInstance().setCropType(CameraUtils.CropType.Square).cropPicture(PersonActivity.this, path);
            }

            @Override
            public void selectPictureFinish(String path) {
                CameraUtils.getInstance().setCropType(CameraUtils.CropType.Square).cropPicture(PersonActivity.this, path);
            }

            @Override
            public void cropPictureFinish(String path) {
                KLog.e(path);
                commitPic(path);
            }
        });
    }

    private void commitPic(String path) {
        mApiHelper.commitPic(path, new Observer<BaseBean<UserInfoBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<UserInfoBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    ViewUtils.loadCircleImage(mContext,baseBean.getData().getUrl(),ivTx);
                    modifyTx(baseBean.getData().getId());
                }else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void modifyTx(String id) {
        mApiHelper.modifyPersonInfo(uid, id, "", "", "", "", "", new Observer<BaseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean baseBean) {
                ToastUtils.showToast(baseBean.getMs());
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){

                    onResume();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }



    //地址选择器
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {


                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        //                        Toast.makeText(RealNameActivity.this,"开始解析数据",Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    //                    Toast.makeText(RealNameActivity.this,"解析数据成功",Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    //                    Toast.makeText(RealNameActivity.this,"解析数据失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    /**
     * 城市三级联动
     */
    private void selectAddress() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                province =options1Items.get(options1).getPickerViewText();
                city = options2Items.get(options1).get(options2);
                county = options3Items.get(options1).get(options2).get(options3);

                showAddressSure();

            }
        }).setDividerColor(Color.GRAY)
                .setCancelColor(R.color.red_color)
                .setSubmitColor(R.color.red_color)
                //.setTextColorCenter(getResources().getColor(R.color.blue)) //设置选中项文字颜色
                .setContentTextSize(16)
                //.setTitleText("城市选择")
                .setOutSideCancelable(true)// default is true
                .build();
        //默认选择河南省
        pvOptions.setSelectOptions(15);
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void showAddressSure() {
        AlertViewFactory.getInstance().getContentAlert(this, "确认所在区域",province + city + county, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if(position == 0){
                    mApiHelper.modifyPersonInfo(uid, "", "", "", province, city, county, new Observer<BaseBean>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(BaseBean baseBean) {
                            ToastUtils.showToast(baseBean.getMs());
                            if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                                add_status = 1;
                                tvQy.setText(province + city + county);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
                }
            }
        }).show();
    }


    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        handler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

}
